package com.lych.dubbo.api;

import com.lych.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.Queue;

@DubboService
public class FriendApiImpl implements FriendApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 将好友关系保存
     * @param friendId
     * @param userId
     */
    @Override
    public void save(Long friendId, Long userId) {
        //保存自己关于好友的数据
        Query query1 = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        //判断是否存在，不存在就保存
        if (!mongoTemplate.exists(query1, Friend.class)){
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }

        //保存好友关于自己的数据
        Query query2 = Query.query(Criteria.where("friendId").is(userId).and("userId").is(friendId));
        //判断是否存在，不存在就保存
        if (!mongoTemplate.exists(query2, Friend.class)){
            Friend friend = new Friend();
            friend.setUserId(friendId);
            friend.setFriendId(userId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
    }

    /**
     * 当前用户的好友
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Friend> findByUserId(Long userId, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("userId").is(userId))
                .skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        return friends;
    }
}
